from fastapi import APIRouter, HTTPException
from app.schemas.face import FaceDescriptor, verifyFaceDescriptor
from app.schemas.auth import PasswordAuth
from app.services import auth
import logging

logger = logging.getLogger(__name__)

router = APIRouter()


@router.post("/verify")
def verify_face(face_data: verifyFaceDescriptor):
    """
    人脸验证
    :param face_data:
    :return:
    """
    try:
        descriptor = face_data.descriptor
        user_name = auth.verify_face_descriptor(descriptor)
        if user_name:
            logger.info(f"人脸验证成功，用户名: {user_name}")
            return {"success": True, "message": "Face verification successful", "user_name": user_name}
        else:
            logger.warning("人脸验证失败，未找到匹配的人脸")
            raise HTTPException(status_code=401, detail="Face verification failed, no matching face found")
    except Exception as e:
        logger.error("人脸验证过程中出现错误: %s", str(e))
        raise


@router.post("/register")
def register_face(face_data: FaceDescriptor):
    """
    人脸注册
    :param face_data:
    :return:
    """
    try:
        descriptor = face_data.descriptor
        user_name = face_data.userName
        user_id = auth.save_face_descriptor(user_name=user_name, descriptor=descriptor)
        logger.info("人脸注册成功，用户ID: %s", user_id)
        return {"success": True, "message": "Face registration successful", "user_id": user_id}
    except Exception as e:
        logger.error("人脸注册过程中出现错误: %s", str(e))
        raise


@router.post("/login")
def login_with_password(password_data: PasswordAuth):
    """
    备用密码登录
    :param password_data:
    :return:
    """
    try:
        if auth.verify_backup_password(password_data.password):
            logger.info("密码验证成功，使用备用密码登录")
            return {"success": True, "message": "Password verification successful", "access_token": "backup-user"}
        else:
            logger.warning("密码验证失败")
            raise HTTPException(status_code=401, detail="Password verification failed")
    except Exception as e:
        logger.error("密码登录过程中出现错误: %s", str(e))
        raise


@router.get("/faces")
def get_faces():
    """
    获取所有人脸
    :return:
    """
    try:
        faces = auth.get_all_faces()
        logger.info("获取所有已注册的人脸，数量: %d", len(faces))
        return {"success": True, "faces": faces}
    except Exception as e:
        logger.error("获取所有已注册人脸时出现错误: %s", str(e))
        raise